using System.Windows;
using System.Windows.Interactivity;
using ChessKit.Common;

namespace ChessKit.Ui
{
  public class AddColorizerBehavior : Behavior<BoardBorderControl>
  {
    public static readonly DependencyProperty ColorizerProperty =
      DependencyProperty.Register("Colorizer", typeof (IColorizer), 
      typeof (AddColorizerBehavior), new PropertyMetadata(null,OnColorizerPropertyChanged));

    private static void OnColorizerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      ((AddColorizerBehavior) d).OnColorizerPropertyChanged((IColorizer) e.OldValue, (IColorizer) e.NewValue);
    }

    private void OnColorizerPropertyChanged(IColorizer oldValue, IColorizer newValue)
    {
      if (AssociatedObject == null) return;
      if (oldValue != null)
      {
        AssociatedObject.Colorizers.Remove(oldValue);
      }
      if (newValue != null)
      {
        AssociatedObject.Colorizers.Add(newValue);
      }
    }

    public IColorizer Colorizer
    {
      get { return (IColorizer) GetValue(ColorizerProperty); }
      set { SetValue(ColorizerProperty, value); }
    }
    protected override void OnAttached()
    {
      if (Colorizer != null)
      {
        AssociatedObject.Colorizers.Add(Colorizer);
      }
    }
    protected override void OnDetaching()
    {
      if (Colorizer != null)
      {
        AssociatedObject.Colorizers.Remove(Colorizer);
      }
    }
  }
}